#include <bits/stdc++.h>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;

    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
private:

    static ListNode *removeHead(ListNode **head) {
        auto tmp = (*head);
        (*head) = (*head)->next;
        delete tmp;
        cout << (long long) *head << endl;
        return *head;
    }

    static ListNode *remove(ListNode **p) {
        auto tmp = (*p)->next;
        (*p)->next = (*p)->next->next;
        delete tmp;
        return *p;
    }

public:

    static void add(ListNode **head, int val) {
        if (*head == nullptr)
            *head = new ListNode(val);
        else {
            auto p = *head;
            while (p->next) p = p->next;
            p->next = new ListNode(val);
        }
    }

    static void printList(ListNode *head) {
        auto p = head;
        while (p) {
            cout << p->val << " ";
            p = p->next;
        }
        cout << endl;
    }

    ListNode *removeElements(ListNode *head, int val) {
        while (head && head->val == val) {
            head = removeHead(&head);
        }
        if (head == nullptr)return nullptr;
        auto p = head;
        do {
            while (p->next && p->next->val == val)
                p = remove(&p);
            p = p->next;
        } while (p);
        return head;
    }
};

int main() {
    ListNode *head = nullptr;
    Solution solution;
    vector<int> test = {1,6, 6, 6, 6, 6, 6};
    for (auto num : test) {
        Solution::add(&head, num);
        Solution::printList(head);
    }
    solution.removeElements(head, 6);
    Solution::printList(head);
}
